package com.czl.module_storehouse.activity.remand.damage;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.czl.base.data.bean.tengyun.BorrowBean;
import com.czl.base.data.bean.tengyun.LocatListBean;
import com.czl.base.data.bean.tengyun.ProductBean;
import com.czl.base.data.bean.tengyun.ReceiveBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.mvp.view.SimpleView;
import com.czl.module_base.utils.NumberUtils;
import com.czl.module_base.utils.ParcelHelper;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.base.BaseOperationLocationActivity;
import com.czl.module_storehouse.activity.scan.ScanActivity;
import com.czl.module_storehouse.adapter.DamageRegisProductAdapter;
import com.czl.module_storehouse.bean.RemandBean;
import com.czl.module_storehouse.databinding.ActivityDamageRegisProductBinding;
import com.czl.module_storehouse.databinding.FooterCommonRemarkBinding;
import com.czl.module_storehouse.event.DamageRegisEvent;
import com.czl.module_storehouse.event.DamageRegisPostEvent;
import com.czl.module_storehouse.event.DamageRegisSearchEvent;
import com.czl.module_storehouse.mvp.presenter.ProductPresenter;
import com.czl.module_storehouse.mvp.presenter.StorehouseLocationPresenter;
import com.czl.module_storehouse.mvp.view.StorehouseLocationView;
import com.czl.module_storehouse.utils.QrCodeRuleUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;


/**
 * @author xubin
 */
public class DamageRegisProductActivity extends BaseOperationLocationActivity<ActivityDamageRegisProductBinding> implements SimpleView, StorehouseLocationView {

    private SortBean mSortBean;
    private List<ProductBean> mReceiveProductViewList;
    private List<ProductBean> mBorrowProductViewList;
    private final HashSet<Integer> mSelectProductIds = new HashSet<>();
    private DamageRegisProductAdapter mAdapter;
    private int mMaxNum;
    private int mMinNum;
    private int mCurdamageNum;
    private int mLostNum;
    private int mDamageNum;

    /**
     * 上一次选择的位置
     */
    private String mLastLocation;

    @InjectPresenter
    ProductPresenter mProductPresenter;
    @InjectPresenter
    StorehouseLocationPresenter mStorehouseLocationPresenter;
    private FooterCommonRemarkBinding mFooterBinding;

    @Override
    protected ActivityDamageRegisProductBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityDamageRegisProductBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mToolBinding.toolbarContentTitle.setText("损坏登记");
        mAdapter = new DamageRegisProductAdapter(R.layout.item_remand_damage_product, new ArrayList<>());
        binding.recyclerView.setAdapter(mAdapter);
        mFooterBinding = FooterCommonRemarkBinding.inflate(getLayoutInflater());
        mAdapter.addFooterView(mFooterBinding.getRoot());
        initListener();
        EventBus.getDefault().register(this);
    }

    private void setLocationEnable() {
        if (mLostNum > 0 && mDamageNum == 0) {
            binding.tvLocation.setEnabled(false);
            binding.tvLocation.setVisibility(View.GONE);
        } else {
            binding.tvLocation.setEnabled(true);
            if (TextUtils.isEmpty(mLastLocation)) {
                binding.tvLocation.setText("选择存放位置");
            } else {
                binding.tvLocation.setText(mLastLocation);
            }
            binding.tvLocation.setVisibility(View.VISIBLE);
        }
    }

    private void initListener() {
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (R.id.iv_delete == view.getId()) {
                mSelectProductIds.remove(mAdapter.getItem(position).getProductId());
                adapter.removeAt(position);
                mMinNum--;
                mCurdamageNum--;
                binding.layoutQuantity.tvQuantity.setText(String.valueOf(mCurdamageNum));
            }
        });
        binding.layoutQuantity.tvQuantity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                if (NumberUtils.isNumber(text)) {
                    int num = Integer.parseInt(text);
                    if (num > (mMaxNum - mLostNum)) {
                        num = mMaxNum - mLostNum;
                        mDamageNum = num;
                        binding.layoutQuantity.tvQuantity.setText(String.valueOf(num));
                        mCurdamageNum = num;
                    } else if (num < mMinNum) {
                        num = mMinNum;
                        mDamageNum = num;
                        binding.layoutQuantity.tvQuantity.setText(String.valueOf(num));
                        mCurdamageNum = num;
                    } else {
                        mDamageNum = num;
                        mCurdamageNum = num;
                    }
                    binding.layoutQuantity.tvQuantity.setSelection(binding.layoutQuantity.tvQuantity.getText().length());

                    setLocationEnable();
                }
            }
        });

        binding.tvQuantityLose.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                if (NumberUtils.isNumber(text)) {
                    int num = Integer.parseInt(text);
                    if (num > (mMaxNum - mDamageNum)) {
                        num = mMaxNum - mDamageNum;
                        mLostNum = num;
                        binding.tvQuantityLose.setText(String.valueOf(num));
                    } else if (num < 0) {
                        num = 0;
                        mLostNum = num;
                        binding.tvQuantityLose.setText(String.valueOf(num));
                    } else {
                        mLostNum = num;
                    }
                    binding.tvQuantityLose.setSelection(binding.tvQuantityLose.getText().length());

                    setLocationEnable();
                }
            }
        });

        binding.layoutQuantity.textRemove.setOnClickListener(v -> remove());
        binding.layoutQuantity.textAdd.setOnClickListener(v -> add());
        binding.textRemoveLose.setOnClickListener(v -> removeLose());
        binding.textAddLose.setOnClickListener(v -> addLose());
        binding.shadowLayout.setOnClickListener(v -> goScanActivity());
        binding.tvLocation.setOnClickListener(v -> getStorehouseLocatList(true));
        binding.textConfirm.setOnClickListener(v -> submit());
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(DamageRegisEvent event) {
        SortBean sortBean = event.getSortBean();
        if (sortBean == null) {
            return;
        }

        int operationalNum = sortBean.getRemandNum() + (sortBean.getExcNum() == null ? 0 : sortBean.getExcNum());
        initDataBySortBean(sortBean, operationalNum, R.string.wait_return_num_placeholder);

        RemandBean remandBean = event.getRemandBean();
        if (remandBean == null) {
            return;
        }
        ReceiveBean receiveBean = remandBean.getReceiveBean();
        if (receiveBean != null) {
            mReceiveProductViewList = receiveBean.getReceiveProductViewList();
        }
        BorrowBean borrowBean = remandBean.getBorrowBean();
        if (borrowBean != null) {
            mBorrowProductViewList = borrowBean.getBorrowProductViewList();
        }
    }

    private void initDataBySortBean(SortBean sortBean, int remandNum, int p) {
        mSortBean = ParcelHelper.copy(sortBean);
        binding.tvSortName.setText(sortBean.getSortName());
        //完好数量
        int stockNum = sortBean.getProductCount();
        mMaxNum = remandNum - stockNum;
        binding.tvReturnNum.setText(getString(p, remandNum));
        binding.tvIntactNum.setText(getString(R.string.intact_num_placeholder, stockNum));

        mFooterBinding.etRemark.setText(sortBean.getDamageComment());
        binding.tvLocation.setText(mSortBean.getExcLocatName());

        int damageNum = mSortBean.excNum() - mSortBean.excLossesNum();
        binding.layoutQuantity.tvQuantity.setText(String.valueOf(damageNum));
        binding.tvQuantityLose.setText(String.valueOf(mSortBean.getExcLossesNum() == null ? 0 : mSortBean.getExcLossesNum()));
        if (mSortBean.getExcProductList() != null) {
            mAdapter.addData(mSortBean.getExcProductList());
        }
        mDamageNum = damageNum;
        mLostNum = mSortBean.excLossesNum();

        mLastLocation = sortBean.getExcLocatName();
        setLocationEnable();
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(DamageRegisSearchEvent event) {
        SortBean sortBean = event.getSortBean();
        if (sortBean == null) {
            return;
        }
        initDataBySortBean(sortBean, sortBean.getRemandNum(), R.string.wait_return_num_placeholder);
    }

    protected final ActivityResultLauncher<Intent> mLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getData() != null) {
                    String stringResult = result.getData().getStringExtra(ScanActivity.RESULT);
                    getProductInfoByCode(QrCodeRuleUtils.handleStorehouseProductResult(stringResult));
                }
            });

    private void goScanActivity() {
        if (mMaxNum > (mCurdamageNum + mLostNum)) {
            mLauncher.launch(new Intent(getContext(), ScanActivity.class));
        } else {
            showToast("损坏物品不能大于待归还物品");
        }
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (ProductPresenter.TAG_PRODUCT_USE_INFO_BY_CODE.equals(httpResponse.getRequestTag())) {
            ProductBean productBean = (ProductBean) httpResponse.getData();
            if (productBean == null) {
                showToast("物品信息错误");
                return;
            }
            if (setResultProduct(productBean)) {
                return;
            }

            boolean add = mSelectProductIds.add(productBean.getProductId());
            if (add) {
                productBean.setManufactureDate(null);
                mAdapter.addData(productBean);
                mSelectProductIds.add(productBean.getProductId());
                mMinNum++;
                mCurdamageNum++;
                binding.layoutQuantity.tvQuantity.setText(String.valueOf(mCurdamageNum));
            } else {
                showToast("该物品已添加");
            }
        }
    }

    protected boolean setResultProduct(ProductBean productBean) {
        if (mSortBean != null) {
            if (mSortBean.isLocatListProducts(productBean)) {
                showToast("该物品已扫完好");
                return true;
            }
            if (!productBean.isSortProduct(mSortBean.getSortId())) {
                showToast("不是该归还物品");
                return true;
            }
        }

        if (mBorrowProductViewList != null) {
            if (!productBean.isReturnProduct(mBorrowProductViewList)) {
                showToast("该物品不是待归还物品");
                return true;
            }
        }
        if (mReceiveProductViewList != null) {
            if (!productBean.isReturnProduct(mReceiveProductViewList)) {
                showToast("该物品不是待归还物品");
                return true;
            }
        }

        if (!productBean.isRemand()) {
            showToast("该物品不是待归还物品");
            return true;
        }
        return false;
    }

    protected void getProductInfoByCode(String productCode) {
        if (mProductPresenter != null) {
            mProductPresenter.getProductUseInfoByCode(productCode);
        }
    }

    private void submit() {
        if (mSortBean == null) {
            return;
        }
        int excNum = 0;
        String textDamage = binding.layoutQuantity.tvQuantity.getText().toString();
        if (NumberUtils.isNumber(textDamage)) {
            excNum += Integer.parseInt(textDamage);
        }
        String textLose = binding.tvQuantityLose.getText().toString();
        if (NumberUtils.isNumber(textLose)) {
            excNum += Integer.parseInt(textLose);
            mSortBean.setExcLossesNum(Integer.parseInt(textLose));
        }
        mSortBean.setExcProductList(mAdapter.getData());
        mSortBean.setExcNum(excNum);
        mSortBean.setDamageComment(mFooterBinding.etRemark.getText().toString());
        EventBus.getDefault().postSticky(new DamageRegisPostEvent(mSortBean));
        finish();
    }

    @Override
    protected StorehouseLocationPresenter getLocationPresenter() {
        return mStorehouseLocationPresenter;
    }

    @Override
    protected boolean callBackModel(LocatListBean bean) {
        boolean call = super.callBackModel(bean);
        if (!call) {
            showToast("该库位已添加");
            return false;
        }
        mLastLocation = bean.getStorehouseLocatName();
        binding.tvLocation.setText(bean.getStorehouseLocatName());
        if (mSortBean != null) {
            mSortBean.setExcLocatId(bean.getStorehouseLocatId());
        }
        if (mSortBean != null) {
            mSortBean.setExcLocatName(bean.getStorehouseLocatName());
        }
        return true;
    }

    private void remove() {
        String text = binding.layoutQuantity.tvQuantity.getText().toString();
        if (NumberUtils.isNumber(text)) {
            int num = Integer.parseInt(text);
            if (num <= mMinNum) {
                num = mMinNum;
            } else {
                num--;
            }
            mDamageNum = num;
            binding.layoutQuantity.tvQuantity.setText(String.valueOf(num));
        }
    }

    private void add() {
        String text;
        text = binding.layoutQuantity.tvQuantity.getText().toString();
        if (NumberUtils.isNumber(text)) {
            int num = Integer.parseInt(text);
            if (num >= (mMaxNum - mLostNum)) {
                num = mMaxNum - mLostNum;
            } else {
                num++;
            }
            mDamageNum = num;
            binding.layoutQuantity.tvQuantity.setText(String.valueOf(num));
            mCurdamageNum = num;
        }
    }

    private void removeLose() {
        String text;
        text = binding.tvQuantityLose.getText().toString();
        if (NumberUtils.isNumber(text)) {
            int num = Integer.parseInt(text);
            if (num <= 0) {
                num = 0;
            } else {
                num--;
            }
            mLostNum = num;
            binding.tvQuantityLose.setText(String.valueOf(num));
        }
    }

    private void addLose() {
        String text;
        text = binding.tvQuantityLose.getText().toString();
        if (NumberUtils.isNumber(text)) {
            int num = Integer.parseInt(text);
            if (num >= (mMaxNum - mDamageNum)) {
                num = mMaxNum - mDamageNum;
            } else {
                num++;
            }
            mLostNum = num;
            binding.tvQuantityLose.setText(String.valueOf(num));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mFooterBinding != null) {
            mFooterBinding.unbind();
        }
    }
}
